package org.springside.modules.utils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
/**
 * 定义一个关于Ajax请求处理的工具类，针对jquery<br>
 * 对不起白衣，破坏了你spingside core的纯洁
 * @author QUANXIWEI
 *
 */
public class AjaxJQueryUtils {
	public static void print(HttpServletResponse response, String info)
			throws IOException {
		try {
			response.getWriter().print(info);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 读取请求参数转换JSONObject对象
	 * 
	 * @param request
	 *            HttpServletRequest 对象
	 * @return json格式的String对象
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static JSONObject readJson(HttpServletRequest request) throws Exception {
		JSONObject jsonObject = new JSONObject();
		try {
			Map parameterMap = request.getParameterMap();
			// 通过循环遍历的方式获得key和value并set到JSONObject中
			Iterator paIter = parameterMap.keySet().iterator();
			while (paIter.hasNext()) {
				String key = paIter.next().toString();
				String[] values = (String[]) parameterMap.get(key);
				jsonObject.accumulate(key, values[0]);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return jsonObject;
	}
}
